package com.insurance.modules.claim.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.insurance.common.common.ResponseData;
import com.insurance.common.enums.ResponseEnum;
import com.insurance.common.utils.R;
import com.insurance.modules.claim.constants.ClaimConstants;
import com.insurance.modules.claim.entity.ClaimCaseEntity;
import com.insurance.modules.claim.entity.ClaimSettlementEntity;
import com.insurance.modules.claim.service.ClaimCaseService;
import com.insurance.modules.claim.service.ClaimSettlementService;
import com.insurance.modules.sys.controller.AbstractController;
import com.insurance.modules.sys.entity.SysUserEntity;
import com.insurance.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;


/**
 * 案件理赔表
 *
 * @author weiruifeng
 * @email
 * @date 2021-09-24 17:42:47
 */
@RestController
@RequestMapping("claim/claimsettlement")
@Api(tags = "案件理赔")
@Slf4j
public class ClaimSettlementController extends AbstractController {
    @Autowired
    private ClaimSettlementService claimSettlementService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ClaimCaseService claimCaseService;

    /**
     * 案件理赔记录列表
     */
    @PostMapping("/list4case")
    @RequiresPermissions("claim:claimsettlement:list4case")
    @ApiOperation(value = "案件理赔记录列表", notes = "根据案件id查询案件理赔记录列表")
    public ResponseData<List<ClaimSettlementEntity>> pageList(@RequestParam(value = "caseId") String caseId) {
        List<ClaimSettlementEntity> list = claimSettlementService.list4case(caseId, null);
        return ResponseData.success(list);
    }

    /**
     * 理赔经理重新分配理赔专员
     */
    @PostMapping("/reassign")
    @RequiresPermissions("claim:claimsettlement:reassign")
    @ApiOperation(value = "理赔经理重新分配理赔专员", notes = "理赔经理重新分配理赔专员")
    @Transactional
    public R reassign(@RequestParam(value = "id") String id, @RequestParam(value = "newUserId") String newUserId) {
        // 1.更新理赔记录表
        SysUserEntity sysUser = sysUserService.getById(newUserId);
        logger.info("【重新分配的理赔专员】，新理赔专员信息：" + JSON.toJSONString(sysUser));
        if (sysUser == null) {
            logger.error("【重新分配的理赔专员】信息为空，userId：" + newUserId);
            return R.error("【重新分配的理赔专员】信息为空，userId：" + newUserId);
        }
        Long userId = sysUser.getUserId();
        String username = sysUser.getUsername();
        ClaimSettlementEntity claimSettlement = claimSettlementService.getById(id);
        logger.info("【重新分配的理赔专员】，原理赔记录：" + JSON.toJSONString(claimSettlement));
        claimSettlement.setAcceptorId(userId);
        claimSettlement.setAcceptorName(username);
        claimSettlementService.updateById(claimSettlement);
        //2.更新案件表首次或二次理赔专员信息
        String caseId = claimSettlement.getCaseId();
        ClaimCaseEntity claimCase = claimCaseService.getById(caseId);
        Integer order = claimSettlement.getSettlementOrder();
        if (ClaimConstants.SETTLEMENT_ORDER_FIRST.equals(order)) {
            // 首次理赔
            claimCase.setFirstAcceptorId(userId);
            claimCase.setFirstAcceptorName(username);
        } else {
            // 二次理赔
            claimCase.setSecondAcceptorId(userId);
            claimCase.setSecondAcceptorName(username);
        }
        claimCaseService.updateById(claimCase);
        return R.ok();
    }

    /**
     * 根据理赔记录id获取
     */
    @PostMapping("/query/{csId}")
    //@RequiresPermissions("claim:claimsettlement:list4case")
    @ApiOperation(value = "案件理赔记录", notes = "根据id查询理赔记录")
    public ResponseData<JSONObject> queryById(@PathVariable("csId") String csId) {
        ClaimSettlementEntity claimSettlement = claimSettlementService.getById(csId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("claimSettlement", claimSettlement);
        jsonObject.put("hasSecond", false);
        if(null != claimSettlement && StringUtils.isNotBlank(claimSettlement.getCaseId())){
            List<ClaimSettlementEntity> list = claimSettlementService.list4case(claimSettlement.getCaseId(), ClaimConstants.SETTLEMENT_ORDER_SECOND);
            jsonObject.put("hasSecond", CollectionUtils.isNotEmpty(list));
        }
        return ResponseData.success(jsonObject);
    }

    @PostMapping("/second")
    @ApiOperation(value = "二次理赔", notes = "二次理赔")
    @Transactional
    public ResponseData<ClaimSettlementEntity> secondSettlement(@RequestParam(value = "caseId") String caseId){
        if(StringUtils.isBlank(caseId)){
            return ResponseData.error(ResponseEnum.ERROR.getCode(), "参数错误!");
        }
        List<ClaimSettlementEntity> list = claimSettlementService.list4case(caseId, ClaimConstants.SETTLEMENT_ORDER_SECOND);
        if(CollectionUtils.isNotEmpty(list)){
            return ResponseData.error(ResponseEnum.ERROR.getCode(), "已存在二次理赔记录!");
        }
        Date date = new Date();
        ClaimSettlementEntity claimSettlement = new ClaimSettlementEntity();
        claimSettlement.setCaseId(caseId);
        claimSettlement.setSettlementOrder(ClaimConstants.SETTLEMENT_ORDER_SECOND);
        claimSettlement.setCaseStatus(ClaimConstants.CLAIM_STATUS_ACCEPT);
        claimSettlement.setAcceptorId(getUserId());
        claimSettlement.setAcceptorName(getUserName());
        claimSettlement.setCreateBy(getUserId());
        claimSettlement.setCreateTime(date);
        claimSettlement.setUpdateBy(getUserId());
        claimSettlement.setUpdateTime(date);
        claimSettlementService.save(claimSettlement);
        ClaimCaseEntity claimCaseEntity = claimCaseService.getById(caseId);
        claimCaseEntity.setSecondStatus(ClaimConstants.CLAIM_STATUS_ACCEPT);
        claimCaseEntity.setCaseStatus(ClaimConstants.CASE_STATUS_ACCEPT);
        claimCaseEntity.setSecondAcceptorId(getUserId());
        claimCaseEntity.setSecondAcceptorName(getUserName());
        claimCaseEntity.setUpdateBy(getUserId());
        claimCaseEntity.setUpdateTime(date);
        claimCaseService.updateById(claimCaseEntity);
        return ResponseData.success(claimSettlement);
    }

    @PostMapping("/cancel")
    @ApiOperation(value = "撤销案件", notes = "撤销案件")
    @Transactional
    public ResponseData<ClaimSettlementEntity> cancelSettlement(@RequestParam(value = "csId") String csId){
        if(StringUtils.isBlank(csId)){
            return ResponseData.error(ResponseEnum.ERROR.getCode(), "参数错误!");
        }
        ClaimSettlementEntity claimSettlement = claimSettlementService.getById(csId);
        claimSettlement.setCaseStatus(ClaimConstants.CLAIM_STATUS_CANCELLED);
        claimSettlement.setUpdateBy(getUserId());
        Date updateTime = new Date();
        claimSettlement.setUpdateTime(updateTime);
        claimSettlementService.updateById(claimSettlement);
        ClaimCaseEntity caseEntity = new ClaimCaseEntity();
        caseEntity.setId(claimSettlement.getCaseId());
        if(ClaimConstants.SETTLEMENT_ORDER_FIRST.intValue() == claimSettlement.getSettlementOrder()){
            caseEntity.setFirstStatus(ClaimConstants.CLAIM_STATUS_CANCELLED);
        }else{
            caseEntity.setSecondStatus(ClaimConstants.CLAIM_STATUS_CANCELLED);
        }
        //首次理赔同步更改案件状态
        caseEntity.setCaseStatus(ClaimConstants.CASE_STATUS_CANCELLED);
        caseEntity.setUpdateTime(updateTime);
        caseEntity.setUpdateBy(getUserId());
        claimCaseService.updateById(caseEntity);
        return ResponseData.success(claimSettlement);
    }


}
